//
//  NSUserDefaults+YS.m
//  luGongPro
//
//  Created by 王庆学 on 2017/7/31.
//  Copyright © 2017年 王庆学. All rights reserved.
//

#import "NSUserDefaults+YS.h"

static NSString *const didMigrateToAppGroupsKey = @"migrate_to_group.com.jxyr.lugong";

@implementation NSUserDefaults (YS)

+ (NSString *) didMigrateToAppGroupsKey{
    return [didMigrateToAppGroupsKey copy];
}

#pragma mark --不太懂
+ (void) migrateOldUserDefaultToGroup{
    if (![[NSUserDefaults userDefaultWithGroup] boolForKey:didMigrateToAppGroupsKey]){
        NSDictionary *oldDefaults = [[NSUserDefaults standardUserDefaults] dictionaryRepresentation];
        for (id key in oldDefaults.allKeys){
            [[NSUserDefaults userDefaultWithGroup] setObject:oldDefaults[key] forKey:key];
        }
        [[NSUserDefaults userDefaultWithGroup] setBool:YES forKey:didMigrateToAppGroupsKey];
        [[NSUserDefaults userDefaultWithGroup] synchronize];
        
        NSString *appDomain = [[NSBundle mainBundle] bundleIdentifier];
        [[NSUserDefaults standardUserDefaults] removePersistentDomainForName:appDomain];
    }
}

+ (instancetype) userDefaultWithGroup{
    return [[NSUserDefaults alloc] initWithSuiteName:[NSUserDefaults userDefaultGroup]];
}

+ (NSString *)userDefaultGroup{
    return @"group.com.jxyr.lugong";
}

+ (void)saveObject:(id)obj forKey:(NSString *)key{
    [[NSUserDefaults userDefaultWithGroup] setObject:obj forKey:key];
    [[NSUserDefaults userDefaultWithGroup] synchronize];
}

+ (id)getObjectForKey:(NSString *)key{
    id obj = [[NSUserDefaults userDefaultWithGroup] objectForKey:key];
    return obj;
}

+ (void)removeObjectForKey:(NSString *)key{
    [[NSUserDefaults userDefaultWithGroup] removeObjectForKey:key];
    [[NSUserDefaults userDefaultWithGroup] synchronize];
}

@end
